﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Xml.Linq;

namespace LdCms.Common.Utility
{
    /// <summary>
    /// 
    /// </summary>
    public partial class Utility
    {
        /// <summary>
        /// 验证字符串是否为XML
        /// </summary>
        /// <returns></returns>
        public static bool IsXml(string xml)
        {
            try
            {
                XDocument xDoc = XDocument.Parse(xml);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        /// XMl字典排序
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static SortedDictionary<string, string> XmlToSortedDictionary(string xml)
        {
            try
            {
                SortedDictionary<string, string> sParams = new SortedDictionary<string, string>();
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(xml);
                System.Xml.XmlElement root = doc.DocumentElement;
                int len = root.ChildNodes.Count;
                for (int i = 0; i < len; i++)
                {
                    string name = root.ChildNodes[i].Name;
                    if (!sParams.ContainsKey(name))
                    {
                        sParams.Add(name.Trim(), root.ChildNodes[i].InnerText.Trim());
                    }
                }
                return sParams;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

        }
        /// <summary>
        /// 字典转XML
        /// </summary>
        /// <param name="keyValues"></param>
        /// <returns></returns>
        public static string SortedDictionaryToXml(SortedDictionary<string, string> keyValues)
        {
            try
            {

                StringBuilder sb = new StringBuilder();
                sb.Append("<xml>");
                foreach (KeyValuePair<string, string> temp in keyValues)
                {
                    sb.Append(string.Format("<{0}><![CDATA[{1}]]></{0}>", temp.Key, temp.Value.Trim()));
                }
                sb.Append("</xml>");
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// XML 字符串 转实体模型
        /// </summary>
        /// <typeparam name="T">转换实体</typeparam>
        /// <param name="xml">传入xml字符串</param>
        /// <returns></returns>
        public static T XmlToEntity<T>(this string xml) where T : new()
        {
            try
            {
                T entity = new T();
                XDocument xDoc = XDocument.Parse(xml);
                XElement root = xDoc.Root;
                foreach (XElement element in root.Elements())
                {
                    string nodeName = element.Name.ToString();
                    string nodeValue = element.Value;
                    foreach (PropertyInfo property in entity.GetType().GetProperties())
                    {
                        if (nodeName.ToLower() == property.Name.ToLower())
                        {
                            if (property.PropertyType == typeof(Int32))
                                property.SetValue(entity, IsNum(nodeValue, 0));
                            else
                                property.SetValue(entity, nodeValue);
                        }
                    }
                }
                return entity;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 实体转XML
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string EntityToXml<T>(this T obj)
        {
            try
            {
                string result = string.Format("<xml>");
                foreach (PropertyInfo property in obj.GetType().GetProperties())
                {
                    string name = property.Name;
                    var value = property.GetValue(obj, null);
                    if (value != null)
                    {
                        if (!string.IsNullOrWhiteSpace(value.ToString()))
                        {
                            result += string.Format("<{0}><![CDATA[{1}]]></{0}>", name, value);
                        }
                    }
                }
                result += string.Format("</xml>");
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }


    }
}
